package com.bw.permission.controller;


import com.bw.permission.common.AjaxResult;
import com.bw.permission.common.BizException;
import com.bw.permission.entity.User;
import com.bw.permission.service.IUserService;
import com.bw.permission.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2021-08-18
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 认证 授权
     * @param user
     * @return
     */
    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            throw new BizException(400, "用户名或密码不能为空");
        }
        //查询用户信息
        User loginUser = iUserService.getByUsername(user.getUsername());
        if (loginUser == null) {
            throw new BizException(400, "用户不存在");
        }
        //停用了吗
        if (!loginUser.getEnabled()) {
            throw new BizException(400, "你的账户已被停用，请联系管理员");
        }
        //判断密码是否正确
        if (!user.getPassword().equals(loginUser.getPassword())) {
            throw new BizException(400, "用户名或密码不能为空");
        }
        //令牌token，每次登录都是唯一，可以用uuid来生成
        String token = jwtUtils.createToken(loginUser.getUsername());
        return AjaxResult.ok(token);
    }

}
